#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unordered_map>
#include <pthread.h>
#include <functional>
#include <signal.h>
#include <cerrno>
#include <cstring>
#include <string>
#include <unistd.h>
#include "Log.hpp"
#include "Comm.hpp"
#include "nocopy.hpp"
#include "InetAddr.hpp"
#include "Thread.hpp"
#include "ThreadPool.hpp"
#include "LockGuard.hpp"

using task_t = std::function<void()>;
using callback_t = std::function<void(int, InetAddr &)>;
const static int default_num = 5;

// class TcpServer;
// class threadData
// {

// public:
//     threadData(const int sock,TcpServer* ptr,struct sockaddr_in &peer) : _sockfd(sock),_tsvr_ptr(ptr),_addr(peer)
//     {
//     }
//     int getSockfd()
//     {
//         return _sockfd;
//     }
//     TcpServer* getTcp_ptr()
//     {
//         return _tsvr_ptr;
//     }

//     ~threadData()
//     {
//         close(_sockfd);
//     }

// private:
//     int _sockfd;
//     TcpServer* _tsvr_ptr;
// public:
//     InetAddr _addr;
// };

class TcpServer : public nocopy
{
public:
    TcpServer(const uint16_t port)
        : _port(port), _isRunning(false)
    {
    }

    void Init()
    {
        // 1.创建listensocket
        _listenSocket = socket(AF_INET, SOCK_STREAM, 0);
        if (_listenSocket < 0)
        {
            lg.LogMessage(Fatal, "_listensocket creat failure errno:%d strerr:%s\n",
                          errno, strerror(errno));
            exit(Socket_Err);
        }
        // 解决一些bind失败的问题，进行socket选项配置
        int opt = 1;
        setsockopt(_listenSocket, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt));
        lg.LogMessage(Debug, "create socket success, sockfd: %d\n", _listenSocket);

        // 2.bind
        struct sockaddr_in local;
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = htonl(INADDR_ANY);
        int n = bind(_listenSocket, CONV(&local), sizeof(local));
        if (n != 0)
        {
            lg.LogMessage(Fatal, "bind failure errno:%d strerr:%s\n",
                          errno, strerror(errno));
            exit(Bind_Err);
        }

        // 3. listen
        int l = listen(_listenSocket, default_num);
        if (l != 0)
        {
            lg.LogMessage(Warning, "listen Failure\n");
        }
        lg.LogMessage(Debug, "Listen success\n");
        // 创建和启动线程池
        ThreadNs::ThreadPool<task_t>::GetInstance()->Start();
    }

    // void Server(int socket)
    // {
    //     char inbuffer[1024];
    //     // 长服务
    //     while (_isRunning)
    //     {
    //         int n = read(socket, inbuffer, sizeof(inbuffer) - 1);
    //         if (n > 0)
    //         {
    //             inbuffer[n] = 0;
    //             std::cout << "client say#:" << inbuffer << std::endl;
    //             std::string response = "server say#:";
    //             response += inbuffer;
    //             write(socket, response.c_str(), response.size());
    //         }
    //         else if (n == 0)
    //         {
    //             lg.LogMessage(Warning, "client quit\n");
    //             return;
    //         }
    //         else
    //         {
    //             lg.LogMessage(Error, "read failure\n");
    //             return;
    //         }
    //     }
    // }

    void Server(int socket, InetAddr &addr)
    {
        char inbuffer[1024];
        // 长服务
        while (_isRunning)
        {
            int n = read(socket, inbuffer, sizeof(inbuffer) - 1);
            if (n > 0)
            {
                inbuffer[n] = 0;
                std::cout << addr.PrintDebug() << "# " << inbuffer << std::endl;
                std::string response = "server say#:";
                response += inbuffer;
                write(socket, response.c_str(), response.size());
            }
            else if (n == 0)
            {
                lg.LogMessage(Warning, "client quit\n");
                return;
            }
            else
            {
                lg.LogMessage(Error, "read failure\n");
                return;
            }
        }
    }

    // static void *threadhander(void *args)//类内方法，有this
    // {
    //     pthread_detach(pthread_self());
    //     threadData* ts = static_cast<threadData*>(args);
    //     ts->getTcp_ptr()->Server(ts->getSockfd(),ts->_addr);
    //     delete ts;
    //     return nullptr;
    // }

    void Start()
    {
        signal(SIGCHLD, SIG_IGN);
        _isRunning = true;
        while (_isRunning)
        {
            // 4.连接
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int socket = accept(_listenSocket, (struct sockaddr *)&(peer), &len);
            if (socket < 0)
            {
                lg.LogMessage(Warning, "accept socket error, errno code: %d, error string: %s\n", errno, strerror(errno));
                continue;
            }
            lg.LogMessage(Debug, "accept success, get n new sockfd: %d\n", socket);
            // v1
            // Server(socket);
            // close(socket);
            // v4 多线程版本
            // threadData* td = new threadData(socket,this,peer);
            // pthread_t tid;
            // pthread_create(&tid, nullptr, threadhander, td);
            // v5 多线程版本
            InetAddr addr(peer);
            task_t t = std::bind(&TcpServer::Routing, this, socket, addr);
            ThreadNs::ThreadPool<task_t>::GetInstance()->Push(t);
            funcs.insert(std::make_pair("DefaultRun", std::bind(&TcpServer::DefaultRun, this, std::placeholders::_1, std::placeholders::_2)));
        }
    }

    void sig_up_task(std::string taskname, callback_t func)
    {
        funcs[taskname] = func;
    }

    std::string Read(int socketfd, InetAddr &addr)
    {
        char type[1024];
        int n = read(socketfd, type, sizeof(type) - 1);
        if (n > 0)
        {
            type[n] = 0;
        }
        else if (n == 0)
        {
            lg.LogMessage(Warning, "client quit\n");
        }
        else
        {
            lg.LogMessage(Error, "read failure\n");
        }
        return type;
    }

    void Routing(int socketfd, InetAddr &addr)
    {
        funcs["DefaultRun"](socketfd, addr);
        std::string type = Read(socketfd, addr);
        lg.LogMessage(Debug, "%s select %s\n", addr.PrintDebug().c_str(), type.c_str());
        if (type == "ping")
            funcs[type](socketfd, addr);
        else if (type == "translate")
            funcs[type](socketfd, addr);
        else if (type == "transform")
            funcs[type](socketfd, addr);
        else
        {
        }
        close(socketfd);
    }

    void DefaultRun(int sockfd, InetAddr &addr)
    {
        std::string server_list = "|";
        for (auto &servername : funcs)
        {
            server_list += servername.first;
            server_list += "|";
        }
        write(sockfd, server_list.c_str(), server_list.size());
    }

    ~TcpServer()
    {
        ThreadNs::ThreadPool<task_t>::GetInstance()->Wait();
    }

private:
    uint16_t _port;
    int _listenSocket;
    bool _isRunning;
    // 任务逻辑
    std::unordered_map<std::string, callback_t> funcs;
};
